<template>
  <div class="notice">
    <div class="search d-between">
      <div class="d-start">
        <div class="d-center" style="margin-right:10px;">
          <el-button
            size="medium"
            type="info"
            @click="getPageData()"
            icon="el-icon-refresh"
            style="width:36px;height:36px;padding:0;"
          ></el-button>
          <el-button size="medium" type="primary" @click="add()">新增</el-button>
        </div>
        <div class="d-center" style="margin-right:10px;">
          <el-button size="medium" :type="selectData.length>0?'danger':'info'" @click="del()">删除</el-button>
        </div>
      </div>
      <div class="d-end">
        <div class="input d-center">
          <el-input size="medium" v-model="title" placeholder="请输入标题">
            <template slot="prepend">检索:</template>
          </el-input>
        </div>
        <!-- <div class="input d-center">
        <span>项目：</span>
        <el-select size="medium" v-model="active" placeholder="请选择">
          <el-option value="1">新建</el-option>
        </el-select>
        </div>-->
        <div class="d-center" style="margin-left:10px;">
          <el-button size="medium" type="info" plain @click="getPageData">搜索</el-button>
          <!-- icon="el-icon-search" -->
          <!-- style="width:36px;height:36px;padding:0;" -->
          <el-button size="medium" type="info" @click="title='';getPageData()" plain>重置</el-button>
        </div>
      </div>
    </div>
    <div class="main">
      <el-table
        :data="tableData"
        style="width: 100%;"
        height="90%"
        @selection-change="handleSelectionChange"
        v-loading="isLoading"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="序号" align="center" width="50">
          <template slot-scope="scope">
            <span>{{(scope.$index + 1)+((page-1)*pageSize)}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="收发文标题" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>
              <el-link
                type="primary"
                @click="view(scope.row),contentDetail=scope.row;dialogFormVisible2=true"
              >{{scope.row.title}}</el-link>

              <!-- <sup v-if="scope.row.is_read == 0"></sup> -->
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="user" label="创建人" align="center"></el-table-column>
        <el-table-column prop="xmmc" label="项目" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="create_time" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="is_top" label="置顶" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_top"
              :active-value="2"
              :inactive-value="1"
              @change="change(scope.$index,scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.sort"
              @change="inputchange(scope.$index,scope.row)"
              :min="0"
              :max="100000"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template slot-scope="scope">
            <!-- <el-button
              size="medium"
              type="success"
              plain
              @click="view(scope.row),contentDetail=scope.row;dialogFormVisible2=true"
            >查看</el-button>-->
            <el-button size="medium" type="primary" plain @click="edit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        @current-change="pageChange"
        :page-size="pageSize"
        :total="total"
        class="d-center"
        style="margin-top:6px"
      ></el-pagination>
    </div>

    <el-dialog
      title="收发文"
      :visible.sync="dialogFormVisible"
      @close="close"
      width="80%"
      top="10"
      :destroy-on-close="true"
    >
      <el-form :model="form" :rules="rules" v-loading="loading">
        <!-- //穿梭框 -->
        <el-form-item prop="name" label="项目" :label-width="'100px'">
          <input
            type="text"
            @click="transfer"
            readonly
            class="el-input__inner"
            v-model="transfer_cn"
            placeholder="请选择项目"
          />
        </el-form-item>
        <!-- <el-form-item prop="name" label="项目" :label-width="'100px'">
          <el-select multiple v-model="form.xm_id" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.xmmc"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <!-- //穿梭框 -->

        <el-form-item prop="name" label="收发文标题" :label-width="'100px'">
          <el-input size="medium" v-model.trim="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="name" label="收发文内容" :label-width="'100px'">
          <el-upload
            :on-success="handleSuccess"
            :show-upload-list="false"
            :format="['jpg','jpeg','png','gif']"
            :max-size="2048"
            multiple
            action="/api/index/uploads2"
            accept=".jpg, .png, .jpeg"
            >
            <Button icon="ios-cloud-upload-outline" ></Button>
          </el-upload>
          <quillEditor v-model.trim="form.content" :options="opation" ref="QuillEditor"></quillEditor>
        </el-form-item>
        <el-form-item prop="is_top" label="置顶" :label-width="'100px'">
          <el-switch v-model="form.is_top" :active-value="2" :inactive-value="1"></el-switch>
        </el-form-item>
        <el-form-item prop="sort" label="排序" :label-width="'100px'">
          <el-input-number size="small" v-model="form.sort" :min="0" :max="100000"></el-input-number>
        </el-form-item>
        <el-form-item prop="name" label="上传附件" :label-width="'100px'">
          <el-row class="d-start">
            <el-col :span="24" class="d-start">
              <uploader
                :fileslists="fileslist"
                :options="options"
                :file-status-text="statusText"
                :fileurl="this.$updata"
                class="uploader-example"
                ref="uploader"
                @file-success="fileSuccess"
                @file-remove="remove"
              ></uploader>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible=false">取 消</el-button>
        <el-button size="medium" type="primary" @click="save()" :loading="loading">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible2" width="80%" top="10">
      <el-form>
        <h2 class="h2">
          <span v-text="contentDetail.title"></span> &nbsp;
          <small v-text="contentDetail.create_time"></small>
        </h2>
        <hr class="hr" />
        <div v-html="contentDetail.content" class="img"></div>
        <uploader
          :fileslists="fileslist"
          :options="options"
          :file-status-text="statusText"
          :fileurl="this.$updata"
          class="uploader-example"
          ref="uploader"
          :app="false"
          style="margin-top:10px"
        ></uploader>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible2=false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- /穿梭框 -->
    <el-dialog
      title="选择项目"
      :visible.sync="dialogFormVisible3"
      :destroy-on-close="true"
      @close="dialogFormVisible3=false"
      width="50%"
      top="10"
    >
      <p style="text-align: center; margin: 0 0 20px"></p>
      <div style>
        <el-transfer
          v-model="transfer_value"
          :props="{
            key: 'id',
            label: 'xmmc'
          }"
          :data="transfer_data"
          filterable
          :titles="['未选择', '已选中']"
          style="display: table;margin: 0 auto;"
        ></el-transfer>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible3=false;">取 消</el-button>
        <el-button size="medium" type="primary" @click="transfer_charge()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- /穿梭框 -->
    <!-- <el-dialog
      title="收发文内容"
      :visible.sync="dialogFormVisible2"
      @close="dialogFormVisible2=false"
      width="80%"
      top="10"
    >
      <h4>收发文标题</h4>
      <div v-html="contentDetail.title" style="margin-bottom:20px"></div>
      <h4>收发文内容</h4>
      <div v-html="contentDetail.content"></div>
    </el-dialog>-->
    <el-dialog
      title="收发文详情"
      :visible.sync="dialogFormVisible2"
      @close="close"
      width="80%"
      top="10"
      :lock-scroll="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <el-form>
        <h2 class="h2">
          <span v-text="contentDetail.title"></span> &nbsp;
          <small v-text="contentDetail.create_time"></small>
        </h2>
        <hr class="hr" />
        <div v-html="contentDetail.content" class="img colora"></div>
        <el-row class="d-start" style="margin-top:20px;">
          <el-col :span="24" class="d-start">
            <uploader
              :fileslists="fileslist"
              :options="options"
              :file-status-text="statusText"
              :fileurl="this.$updata"
              class="uploader-example"
              ref="uploader"
              :app="false"
            ></uploader>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible2=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
// import quillConfig from "../../../config/quill-config";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import mixinsFile from "@/mixins/uploadFile.js";
import { debounce } from "@/plugins/common.js";

export default {
  components: {
    quillEditor,
  },
  name: "notice",
  mixins: [mixinsFile],
  data() {
    return {
      transfer_value: [], //穿梭框选中项目
      transfer_data: [], //穿梭框数据
      transfer_cn: "", //穿梭框选中中文
      projectList: [], //项目列表
      pageSize: 0, //每页显示多少
      total: 0, //总数
      name: "",
      active: "",
      title: "", //搜索条件
      dialogFormVisible: false, //编辑新增弹窗
      dialogFormVisible2: false, //查看弹窗
      dialogFormVisible3: false, //查看弹窗
      contentDetail: "", //查看弹窗中显示内容
      selectData: [], //表格选中的数据
      tableData: [], //表格数据
      form: null, //表单数据
      page: 1, //当前页码
      isLoading: false, //表格加载动画
      fileslist: [],
      options: {
        target: this.$updata + "/api/index/uploads", // '//jsonplaceholder.typicode.com/posts/',
        testChunks: false,
      },
      statusText: {
        success: "成功了",
        error: "出错了",
        uploading: "上传中",
        paused: "暂停中",
        waiting: "等待中",
      },
      loading: false,
      rules: {}, //表单验证
      opation: {
        // placeholder: "请填写描述，字数不超过2000",
        modules: {
          toolbar:{
            handlers: {
              'image': function (value) {
                  if (value) {
                      document.querySelector('.el-upload').click()
                      // alert('自定义图片')
                  } else {
                      this.quill.format('image', false);
                  }
              }
            },
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              // [{ script: "sub" }, { script: "super" }],
              // [{ indent: "-1" }, { indent: "+1" }],
              // [{ direction: "rtl" }],
              // [{ size: ["small", false, "large", "huge"] }],
              // [{ header: [1, 2, 3, 4, 5, 6, false] }],
              // [{ color: [] }, { background: [] }],
              // [{ font: [] }],
              // [{ align: [] }],
              // [{ clean: "源码编辑" }],
              ["link", "image"],
              ["sourceEditor"], //新添加的工具
            ],  // 工具栏
          }
        },
      },
    };
  },
  created() {
    this.formInit();
    this.getPageData();
    this.getProject();
  },
  methods: {
     handleSuccess (res) {
        // 获取富文本组件实例
        let quill = this.$refs.QuillEditor.quill
        // 如果上传成功
        if (res) {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.code)
            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
            this.$message({
              message: '图片插入失败',
              type: "error",
            });
            // 提示信息，需引入Message
            // Message.error('图片插入失败')
        }
    },
    //穿梭框
    transfer() {
      this.dialogFormVisible3 = true;
      this.transfer_value = [];
      if (this.form.xm_id && this.form.xm_id.length > 0) {
        this.form.xm_id.forEach((v) => {
          this.transfer_value.push(parseInt(v));
        });
      }
    },
    transfer_charge() {
      this.transfer_cn = "";
      this.transfer_data.forEach((item) => {
        if (this.transfer_value.indexOf(item.id) > "-1") {
          this.transfer_cn += item.xmmc + " ，";
        }
      });
      this.form.xm_id = this.transfer_value;
      this.dialogFormVisible3 = false;
    },
    //穿梭框
    formInit() {
      this.form = {
        title: "",
        content: "",
        sort: 1,
      };
    },
    getProject() {
      // this.$get("/api/project/index").then(res => {
      //   if (res.code == 200) this.projectList = res.data.list;
      // });
    },
    pageChange(val) {
      this.page = val;
      this.getPageData();
    },
    getPageData() {
      this.isLoading = true;
      this.$get("/api/Engineer/writing", {
        title: this.title,
        page: this.page,
      }).then((res) => {
        this.fileslist = [];
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.total;
          this.pageSize = res.data.limit;
          this.projectList = res.data.project_list;
          this.transfer_data = res.data.project_list;
        }
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
        this.isLoading = false;
      });
    },
    edit(item) {
      this.form = { ...item };
      //穿梭框
      this.transfer_cn = item.xmmc;
      // var ids = [];
      // if (item.xm_id) {
      //   item.xm_id.forEach(v => {
      //     ids.push(parseInt(v));
      //   });
      // }
      // this.form.xm_id = ids;
      //穿梭框

      this.fileslist = item.files ? item.filesarr : [];

      this.dialogFormVisible = true;
    },
    close() {
      //   this.dialogFormVisible = false;
    },
    handleSelectionChange(value) {
      this.selectData = value;
    },
    save() {
      this.loading = true;
      delete this.form.user;
      delete this.form.create_time;
      delete this.form.xmmc;
      delete this.form.link;
      delete this.form.xm_cn;
      delete this.form.is_read;
      delete this.form.filesarr;
      //上传参数组合
      let fileUrl = this.fileslist.map((v) => {
        return v.path;
      });
      this.form.files = fileUrl.join(",");
      //上传参数组合
      this.$post("/api/Engineer/writing_actions", this.form).then((res) => {
        if (res.code == 200) {
          this.getPageData();
          this.$Bus.$emit("refish");
          this.$message({
            message: res.msg,
            type: res.state,
          });
          this.dialogFormVisible = false;
        }
        this.loading = false;
      });
    },
    add() {
      this.dialogFormVisible = true;
      this.formInit();
      //穿梭框
      this.transfer_value = [];
      this.transfer_cn = "";
      //穿梭框
      this.fileslist = [];
    },
    del() {
      if (this.selectData && this.selectData.length > 0) {
        this.$confirm(`是否删除这${this.selectData.length}项`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          let reqs = [];
          this.selectData.map((item) => {
            reqs.push(
              this.$post("/api/Engineer/writing_deletes", { id: item.id }).then(
                (res) => {
                  // this.$message({
                  //   message: res.msg,
                  //   type: res.state
                  // });
                  console.log(res.code);
                }
              )
            );
          });
          Promise.all(reqs).then(() => {
            this.getPageData();
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.$Bus.$emit("refish");
          });
        });
      }
    },
    change: debounce(function (index, data) {
      if (data) {
        var params = {
          id: data.id,
          is_top: data.is_top,
        };
        this.$post("/api/Engineer/writing_istop", params).then((res) => {
          this.$message({
            message: res.msg,
            type: res.state,
          });
          this.getPageData();
          this.$Bus.$emit("refish");
        });
      }
    }),
    inputchange: debounce(function (index, data) {
      if (data) {
        let boolean = new RegExp("^[0-9]*$").test(data.sort);
        if (!boolean) {
          this.$message({
            type: "error",
            message: "请输入正整数或者0",
          });
          this.getPageData();
          return;
        }
        var params = {
          id: data.id,
          sort: data.sort,
        };
        this.$post("/api/Engineer/writing_sort", params).then((res) => {
          this.$message({
            message: res.msg,
            type: res.state,
          });
          this.getPageData();
          this.$Bus.$emit("refish");
        });
      }
    }),
    view(item) {
      if (!item["is_read"]) {
        this.$post("/api/Engineer/writing_read", { id: item.id }).then(
          (res) => {
            if (res.code == 200) {
              item["is_read"] = 1;
            }
          }
        );
      }

      this.fileslist = item.files ? item.filesarr : [];
    },
    //上传组件移除返回
    remove(index) {
      this.fileslist.splice(index, 1);
    },
    //上传成功返回
    fileSuccess(rootFile, file, message, chunk) {
      if (JSON.parse(message).state == "success") {
        this.fileslist.push({
          path: JSON.parse(message).code,
          name: chunk.file.name,
        });
        console.log(this.fileslist);
      } else {
        this.$message({
          message: chunk.file.name + JSON.parse(message).code,
          type: "error",
        });
      }
    },
  },
};
</script>
<style lang="less">
.el-dialog img{
  max-width: 100%;
}
.el-upload,.el-upload-list{
  display: none !important;
}
sup {
  width: 6px;
  height: 6px;
  display: inline-block;
  background: #f00;
  // position: absolute;
  // right: 5px;
  // top: 11px;
  position: relative;
  top: -5px;
  border-radius: 50%;
}
.ql-editor {
  min-height: 200px;
  max-height: 500px;
}
.colora a{
  color: #06c;
  text-decoration: underline;
}
</style>
<style lang="less" scoped>
.notice {
  width: 100%;
  height: calc(100%);
  background: white;
  border-radius: 5px;
  .search {
    width: 100%;
    height: 60px;
    padding: 10px 5px;
    position: relative;
    .input {
      width: 300px;
      margin-left: 10px;
      span {
        flex-shrink: 0;
      }
    }
  }
  .main {
    //   width: 100%;
    height: calc(100% - 50px);
    // overflow-y: scroll;
    // position: absolute
    border: 1px solid #ebeef5;
  }
}
.img {
  font-size: 14px;
  line-height: 2;
  text-indent: 2em;
}
.h2 {
  text-align: center;
  small {
    font-weight: 400;
    font-size: 12px;
  }
}
.hr {
  margin: 10px 0;
  border: 0;
  border-top: 1px #ddd solid;
}
.img img {
  max-width: 100%;
}

.tit {
  width: 100%;
  height: 64px;
}
</style>